package com.hongmeng.teamwork.domain.impl;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.hongmeng.teamwork.convert.TeamworkProjectConvert;
import com.hongmeng.teamwork.convert.UserConvert;
import com.hongmeng.teamwork.domain.ITeamworkProjectDomainService;
import com.hongmeng.teamwork.domain.ITeamworkTaskDomainService;
import com.hongmeng.teamwork.entity.dto.TeamworkProjectDto;
import com.hongmeng.teamwork.entity.event.ProjectMessageEvent;
import com.hongmeng.teamwork.entity.po.TeamworkProject;
import com.hongmeng.teamwork.entity.po.TeamworkTask;
import com.hongmeng.teamwork.entity.po.User;
import com.hongmeng.teamwork.entity.vo.TeamworkProjectVo;
import com.hongmeng.teamwork.enums.IsDeletedFlagEnum;
import com.hongmeng.teamwork.enums.TaskStatusEnum;
import com.hongmeng.teamwork.service.ITeamworkProjectService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Log4j2
@Service
public class TeamworkProjectDomainServiceImpl implements ITeamworkProjectDomainService {

    @Resource
    private ITeamworkProjectService teamworkProjectService;
    @Resource
    private ITeamworkTaskDomainService teamworkTaskDomainService;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(TeamworkProjectDto teamworkProjectDto) {
        TeamworkProject teamworkProject = TeamworkProjectConvert.INSTANCE.convertDtoToEntity(teamworkProjectDto);
        User user = UserConvert.INSTANCE.convertDtoToEntity(teamworkProjectDto.getCreatedUser());
        teamworkProject.setCreatedBy(JSON.toJSONString(user));
        teamworkProject.setCreatedTime(LocalDateTime.now());
        teamworkProject.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        boolean saveStatusFlag = teamworkProjectService.insert(teamworkProject);
        applicationEventPublisher.publishEvent(new ProjectMessageEvent(teamworkProjectDto, teamworkProject, saveStatusFlag));
    }

    @Override
    public List<TeamworkProjectVo> query(TeamworkProjectDto projectDto) {
        TeamworkProject teamworkProject = TeamworkProjectConvert.INSTANCE.convertDtoToEntity(projectDto);
        teamworkProject.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        // 根据 openId 查询自己创建的项目
        List<TeamworkProject> projectList = teamworkProjectService.queryByCondition(teamworkProject);
        // 根据 openId 查询自己的任务集合，再根据任务绑定的项目 id 集合查询项目列表
        List<TeamworkTask> teamworkTaskList = teamworkTaskDomainService.queryByOpenId(projectDto.getOpenId());
        if (CollectionUtils.isNotEmpty(teamworkTaskList)) {
            List<Long> projectIdList = teamworkTaskList.stream().map(TeamworkTask::getProjectId).distinct().collect(Collectors.toList());
            List<Long> projectIdDBList = projectList.stream().map(TeamworkProject::getId).collect(Collectors.toList());
            // 去掉自己创建的项目 id
            projectIdList.removeAll(projectIdDBList);
            if (CollectionUtils.isNotEmpty(projectIdList)) {
                // 根据项目 id 列表查询项目集合
                projectList.addAll(teamworkProjectService.queryByIdList(projectIdList));
            }
        }
        List<TeamworkProjectVo> projectVoList = TeamworkProjectConvert.INSTANCE.convertEntityToVoList(projectList);
        // 组合项目的任务总数和已完成任务数数据
        projectVoList.forEach(projectVo -> {
            TeamworkTask teamworkTask = new TeamworkTask();
            teamworkTask.setProjectId(projectVo.getId());
            // 查询项目任务总数
            projectVo.setTaskTotal(teamworkTaskDomainService.count(teamworkTask));
            // 查询项目已完成任务数
            teamworkTask.setStatus(TaskStatusEnum.FINISHED.getCode());
            projectVo.setFinishedTaskTotal(teamworkTaskDomainService.count(teamworkTask));
            // 设置创建人数据
            projectVo.setCreatedUser(new Gson().fromJson(projectVo.getCreatedBy(), User.class));
        });
        if (log.isInfoEnabled()) {
            log.info("TeamworkProjectDomainServiceImpl.query.voList: {}", JSON.toJSONString(projectVoList));
        }
        return projectVoList;
    }
}
